package com.adamfass.tractorbeam;

import com.jme.input.joystick.Joystick;
import com.jme.input.joystick.JoystickInput;
import com.jme.input.joystick.JoystickInputListener;
import com.jme.math.Vector3f;

public class JoystickFlyingSaucerController implements Controller {
  private static final int TRACTOR_BEAM_BUTTON = 0;
  private static final int DISRUPTOR_POD_BUTTON = 1;
  
  private final Joystick joystick;
  private final int xAxis;
  private final int yAxis;
  
  private boolean disruptorPodWasFired = false;
  
  public JoystickFlyingSaucerController(Joystick joystick) {
    this.joystick = joystick;
    
    int tempXAxis = 0;
    int tempYAxis = 1;
    for (int axis = 0; axis < joystick.getAxisCount(); axis++) {
      final String axisName = joystick.getAxisNames()[axis]
          .toLowerCase()
          .replace("axis", "");
      if (axisName.contains("x")) {
        tempXAxis = axis;
      } else if (axisName.contains("y")) {
        tempYAxis = axis;
      }
    }
    xAxis = tempXAxis;
    yAxis = tempYAxis;
    
    JoystickInput.get().addListener(new JoystickInputListener() {
      public void onButton(Joystick controller, int button, boolean pressed) {
        if (controller == JoystickFlyingSaucerController.this.joystick
            && pressed
            && button == DISRUPTOR_POD_BUTTON) {
          disruptorPodWasFired = true;
        }
      }

      public void onAxis(Joystick controller, int axis, float axisValue) {}
    });
  }
  
  public Vector3f getThrustVector() {
    Vector3f joystickVector = new Vector3f(
        joystick.getAxisValue(xAxis), -joystick.getAxisValue(yAxis), 0);
    if (joystickVector.lengthSquared() > 1) {
      joystickVector = joystickVector.normalize();
    }
    return joystickVector;
  }
  
  public boolean isTractorBeamOn() {
    return joystick.isButtonPressed(TRACTOR_BEAM_BUTTON);
  }
  
  public boolean disruptorPodWasFired() {
    return disruptorPodWasFired;
  }
  
  public void clearEventState() {
    disruptorPodWasFired = false;    
  }
}
